package com.example.ormsqlsplicingframe1.sql.impl;

import com.example.ormsqlsplicingframe1.sql.ConditionSql;
import com.example.ormsqlsplicingframe1.sql.SelectFieldSql;
import com.example.ormsqlsplicingframe1.sql.SelectSql;
import com.example.ormsqlsplicingframe1.utlis.ObjValue;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

public class SelectImpl implements SelectSql {

    private ConditionSql conditionSql = new ConditionImpl();

    private SelectFieldsSql selectFieldSql = new SelectFieldsSql();

    private String table ;

    private LinkedHashMap<String,ConditionSql> joinMap = new LinkedHashMap();
    // sys_user a left join sys_dept b on id = ?
    @Override
    public ConditionSql left(String table) {
        ConditionImpl  condition = new ConditionImpl();

        joinMap.put(" left join "+table,condition);

        return condition;
    }

    @Override
    public ConditionSql right(String table) {

        ConditionImpl  condition = new ConditionImpl();

        joinMap.put(" right join "+table,condition);

        return condition;

    }

    @Override
    public SelectFieldSql fields() {
        return selectFieldSql;
    }

    private String limit;

    @Override
    public SelectSql page(int pageNumber, int pageSize) {
        if (pageNumber == 1){
            pageNumber = 0;
        }else {
            pageNumber +=0;
        }
        this.limit = pageNumber+" , "+pageSize;

        return this;
    }

    @Override
    public SelectSql group(String name) {
        return this;
    }

    @Override
    public SelectSql order(String name, boolean isAsc) {
        return this;
    }

    @Override
    public String getSql() {
        String sql="select "+selectFieldSql.getSql()+" from " +table;
        //left join ss on ${}

        for (Map.Entry<String, ConditionSql> entry : joinMap.entrySet()) {
            final ConditionSql value = entry.getValue();

            sql += entry.getKey()+" on " +value.getSql();
        }

        final String sqlSql = conditionSql.getSql();
        if (sqlSql.length()>0){

            sql +=" where "+ sqlSql;

        }


        if(limit != null){
            sql+=" limit "+limit;
        }

        return sql;
    }

    @Override
    public List<Object> getValues() {
        return conditionSql.getValues();
    }

    @Override
    public SelectSql table(String table) {

        if (!ObjValue.isNotNull(this.table)){
            this.table = table;
        }

        return this;
    }

    @Override
    public ConditionSql where() {
        return conditionSql;
    }
}
